var express = require('express');
const {exec} = require("child_process");
var router = express.Router();

//获取当前时间
const getCurrentTime = (emptyStr = false) => {
  let time = new Date();
  let year = time.getFullYear()
  let mm = time.getMonth() + 1
  mm = mm < 10 ? '0' + mm : mm
  let dd = time.getDate()
  dd = dd < 10 ? '0' + dd : dd
  let hh = time.getHours()
  let mf = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
  let ss = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
  let timeStr = `${year}-${mm}-${dd} ${hh}:${mf}:${ss}`
  if (emptyStr) timeStr = timeStr.replace(/./g, '=')
  return timeStr
}

//执行command命令
const execCommand = (command) => {
  return new Promise((resolve, reject) => {
    if (command.indexOf("cd ") != -1) {
      let dirPath = command.replace("cd ", "");//D:\WorkPlace\Git_Project
      try {
        process.chdir(dirPath);
        resolve({stdout: `进入目录【${process.cwd()}】成功！`})
      } catch (e) {
        reject("进入目录失败！")
      }
    } else {
      try {
        exec(command, (error, stdout, stderr) => {
          let result = {stdout, error, stderr}
          console.log("execCommand=====", result)
          if (stdout) resolve(result)
          if (error) reject(error)
        });
      } catch (e) {
        reject(e)
      }
    }
  })
}

//获取执行命令后的多条结果
const readResultLines = (result) => {
  return result.split("\n").filter(item => item.trim())
}

router.get('/events', async function (req, res, next) {
  res.setHeader('Content-Type', 'text/event-stream;charset=utf-8');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  //'git checkout .'
  //D:\WorkPlace\Git_Project
  let commandList = ['pwd', 'cd D:\\WorkPlace\\Vue_Project1\\AgentManage', 'git branch', 'git pull']
  //循环执行多个命令
  for (let i = 0; i < commandList.length; i++) {
    let commandItem = commandList[i]
    try {
      let result = await execCommand(commandItem)
      let {stdout, error, stderr} = result
      console.log("result====", i, result)
      res.write(`data:${getCurrentTime()} #### ${commandItem}\n\n`)
      readResultLines(stdout).forEach(item => res.write(`data:${getCurrentTime(true)}===== ${item}\n\n`))
    } catch (e) {
      res.write(`data:${getCurrentTime()} #### ${commandItem}\n\n`)
      readResultLines(e.message).forEach(item => res.write(`data:${getCurrentTime(true)}===== ${item}\n\n`))
      return
    }
  }
  res.write(`data:end\n\n`)
  res.end()
});

//=======================================老代码=======================================
//=======================================老代码=======================================
//=======================================老代码=======================================
let setTask = null
let strArr = [
  '所有人,都得死!',
  '犯我德邦者,虽远必诛!',
  '吾所成之事,不可逆也!',
  '一点寒芒先到,随后枪出如龙!',
  '我的剑就是你的剑!',
  '刀下生,刀下死!'
]

router.get('/eventsOld', function (req, res, next) {
  res.setHeader('Content-Type', 'text/event-stream;charset=utf-8');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  let num = 0
  setTask = setInterval(() => {
    res.write(`data:${strArr[num]}\n\n`)
    num++
    if (num > 5) {
      res.write(`data:end\n\n`)
      res.end()
      // res.closed()
      clearInterval(setTask)
      setTask = null
    }
  }, 2000)
});

module.exports = router;
